<template>
  <div class="profile-edit-container">
    <div class="edit-card">
      <div class="card-header">
        <h2>编辑个人资料</h2>
        <button class="close-btn" @click="$router.push('/profile')">×</button>
      </div>
      
      <div class="form-container">
        <!-- Avatar Upload -->
        <div class="avatar-section">
          <div class="avatar-wrapper">
            <img v-if="form.avatar" :src="form.avatar" alt="Avatar" class="avatar-img" />
            <div v-else class="avatar-placeholder">{{ (form.nickname || 'User').charAt(0) }}</div>
            <div class="avatar-overlay" @click="triggerFileInput">
              <span>更换头像</span>
            </div>
          </div>
          <input 
            type="file" 
            ref="fileInput" 
            accept="image/*" 
            style="display: none" 
            @change="handleFileChange" 
          />
        </div>

        <!-- Form Fields -->
        <div class="form-group">
          <label>昵称</label>
          <input v-model="form.nickname" type="text" placeholder="请输入昵称" />
        </div>

        <div class="form-group">
          <label>性别</label>
          <select v-model="form.gender">
            <option value="unknown">保密</option>
            <option value="male">男</option>
            <option value="female">女</option>
          </select>
        </div>

        <div class="form-group">
          <label>手机号</label>
          <input v-model="form.phone" type="tel" placeholder="请输入手机号" />
        </div>

        <div class="form-group">
          <label>个人简介</label>
          <textarea v-model="form.bio" rows="4" placeholder="介绍一下自己..."></textarea>
        </div>

        <div class="form-actions">
          <button class="cancel-btn" @click="$router.push('/profile')">取消</button>
          <button class="save-btn" @click="handleSave" :disabled="loading">
            {{ loading ? '保存中...' : '保存修改' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUser, updateUserInfo, uploadAvatar } from '../api/user'

const router = useRouter()
const loading = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)

const form = reactive({
  nickname: '',
  gender: 'unknown',
  phone: '',
  bio: '',
  avatar: ''
})

// Load current user data
onMounted(async () => {
  try {
    const res: any = await getCurrentUser()
    if (res?.data) {
      form.nickname = res.data.nickname || res.data.username || ''
      form.gender = res.data.gender || 'unknown'
      form.phone = res.data.phone || ''
      form.bio = res.data.bio || ''
      form.avatar = res.data.avatar_url || res.data.avatar || ''
    }
  } catch (e) {
    console.error('Failed to load user info', e)
  }
})

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const file = target.files[0]
    const formData = new FormData()
    formData.append('file', file) // Assuming backend expects 'file'

    try {
      // Show preview immediately (optional, but better UX)
      const reader = new FileReader()
      reader.onload = (e) => {
        if (e.target?.result) form.avatar = e.target.result as string
      }
      reader.readAsDataURL(file)

      // Upload
      const res: any = await uploadAvatar(formData)
      if (res?.data?.url) {
        form.avatar = res.data.url
      }
    } catch (error) {
      console.error('Avatar upload failed', error)
      alert('头像上传失败，请重试')
    }
  }
}

const handleSave = async () => {
  if (!form.nickname.trim()) {
    alert('昵称不能为空')
    return
  }

  loading.value = true
  try {
    await updateUserInfo({
      nickname: form.nickname,
      gender: form.gender,
      phone: form.phone,
      bio: form.bio
    })
    alert('修改成功')
    router.push('/profile')
  } catch (error) {
    console.error('Update failed', error)
    alert('保存失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.profile-edit-container {
  display: flex;
  justify-content: center;
  padding: 40px 20px;
  min-height: calc(100vh - 60px);
  background-color: #F5F7F5;
}

.edit-card {
  width: 100%;
  max-width: 600px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.05);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #F3F4F6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #1F2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #9CA3AF;
  cursor: pointer;
}

.form-container {
  padding: 32px 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 4px solid white;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: #10B981;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  font-weight: bold;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.2s;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 10px 12px;
  border: 1px solid #E5E7EB;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: #10B981;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 16px;
}

.save-btn, .cancel-btn {
  flex: 1;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border: none;
}

.save-btn {
  background: #10B981;
  color: white;
}

.save-btn:disabled {
  background: #A7F3D0;
  cursor: not-allowed;
}

.cancel-btn {
  background: #F3F4F6;
  color: #4B5563;
}
</style>